package com.sysmanagment.service.security;

import java.util.GregorianCalendar;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

import com.sysmanagment.dao.user.UserDAO;
import com.sysmanagment.model.user.Role;
import com.sysmanagment.model.user.User;

@Name("authenticator")
public class AuthenticatorService {
	@Logger
	protected Log log;

	@In(value="userDAO",create=true)
	UserDAO userDAO;

	@In
	Identity identity;
	
	@In
	Credentials credentials;

	@In(required = false, scope = ScopeType.SESSION)
	@Out(required = false, scope = ScopeType.SESSION)
	User loggedUser;

	public boolean authenticate() {
		String username = credentials.getUsername();
		String passwordHash = credentials.getPassword();
		log.debug("authenticating {0}", username);

		loggedUser = userDAO.validateUser(username, passwordHash);
		if (loggedUser != null) {
			loggedUser.setLastAccessOn((GregorianCalendar) GregorianCalendar
					.getInstance());
			userDAO.merge(loggedUser);
			for (Role r : loggedUser.getRoles()) {
				identity.addRole(r.getRolename());
			}
			return true;
		}
		return false;
	}
}
